<?php

class Database {
	var $conn;
	
	function open() {
	
		$dbUser = "xxxx";
		$dbPass = "xxxx";
		$host = "localhost";

		$this->conn = mysql_connect($host, $dbUser, $dbPass);
		if (!$this->conn) {
			echo "Could not connect: " . mysql_error();
		}
		mysql_select_db($dbName, $this->conn);
	}
	function close() {
		mysql_close($this->conn);
	}

	function doQuery($sql) {
//		echo '<br/>'.$sql;
		$ret = mysql_query($sql, $this->conn);
		$error = mysql_errno($this->conn);
		if ( $error ) {
			echo mysql_errno($this->conn) . ": " . mysql_error($this->conn) . "\n" ;
		}
		return $ret;
	}

	function doInsert($sql) {
		$this->doQuery($sql);
		return mysql_insert_id();
	}

	function get($sql, $columnName) {
		$result = $this->doQuery($sql);
		if ( !$result ) {
			return;
		}
		$row = mysql_fetch_array($result);
		if ( $row ) {
			return $row[$columnName];
		}
	}

	function loadList($sql, &$factory, $upTo=10000) {
		$result =& $this->doQuery($sql);
		if ( !$result ) {
			return;
		}
		$list = array();

		$cnt = 0;
		while($row = mysql_fetch_array($result)){
			$obj =& $factory->newInstance();
			$obj->dbLoadCallback($row);
			$list[$cnt] =& $obj;
			$cnt++;
			if ( $cnt > $upTo ) {
				break;
			}
		}
		return $list;
	}

	function selectOne($sql, &$factory) {
		$list =& $this->loadList($sql, $factory);
		$len = count($list);
		if ( $len < 1 ) {
			return NULL;
		} else {
			return $list[0];
		}
	}
	
	function selectCnt($sql) {
		$result =& $this->doQuery($sql);
		if ( !$result ) {
			return 0;
		}
		$cnt = 0;
		while($row = mysql_fetch_array($result)){
			return $row['cnt'];
		}
		
		return 0;
	}
}

?>
